#!/usr/bin/env guile
!#

(use-modules (charting) (charting csv) (ice-9 match)
             ((srfi srfi-1) #:select (filter-map)))

(define (parse-scenario headers data)
  (let lp ((in data) (out (make-list (length headers) '())))
    (if (null? in)
        (map cons
             headers
             (map (lambda (test-data) (filter-map string->number test-data))
                  out))
        (lp (cdr in) (map cons (vector->list (car in)) out)))))

(define (read-scenario file)
  (let ((rows (csv-port->row-list (open-input-file file) #\tab)))
    (if (null? rows)
        '()
        (cons (let ((name (basename file)))
                (if (string-suffix? ".csv" name)
                    (substring name 0 (- (string-length name) 4))
                    name))
              (parse-scenario (vector->list (car rows)) (cdr rows))))))

(define (main args)
  (match args
    ((title output file file* ...)
     (unless (string-suffix? ".png" output)
       ;; Otherwise we would have the possibility of overwriting data.
       ;; That would be bad!
       (format (current-error-port)
               "Error: output name does not end with .png: ~a\n" output)
       (exit 1))
     (make-performance-chart title (map read-scenario (cons file file*))
                             #:write-to-png output))
    (_
     (format (current-error-port)
             "Usage: plot-data.scm title output file1 file2 ...

The files are expected to be in CSV format, with one row of headers,
and one row per run.  The different file names identify the different
scenarios that you want to compare.
")
     (exit 1))))

(main (cdr (command-line)))
